package com.taotao.wechat.game;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.PlayGame;
import com.taotao.rop.database.domain.WechatUser;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;
import com.taotao.wechat.business.User;
import com.taotao.wechat.message.resp.BaseMessage;
import com.taotao.wechat.message.resp.TextMessage;
import com.taotao.wechat.util.MessageUtil;
import com.taotao.wechat.util.ValidateUtil;
import org.apache.commons.lang.StringUtils;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

public abstract class Game {
    protected BaseMessage baseMessage;
    protected String content;
    protected String appKey;
    /**鉴别会员次数中的第一次*/
    public String isMemberTimes = "isMemberTimes";

    /**升级会员成功时返回的提示消息*/
    protected String msgUpgradeMemberSuccess = "恭喜您升级会员成功！";
    /**升级会员失败时返回的提示消息*/
    protected String msgUpgradeMemberFailure = "很遗憾，升级会员失败。" ;
    /**游戏未开始时返回的提示消息*/
    protected String msgGameNotStart = "活动尚未开始，请耐心等待~";
    /**游戏已结束时返回的提示消息*/
    protected String msgGameIsEnd = "活动已经结束，谢谢参与~";
    /**输入游戏名字时，能正常参与游戏的情况下返回的提示消息*/
    protected String msgAfterGameName = "请输入内蒙移动手机号码参与活动";
    /**手机号码不能识别时返回的提示消息*/
    protected String msgTelNotKnow = "您的手机号码未被识别，请耐心等待工作人员审核";
    /**手机号码不是内蒙古移动号码时返回的提示消息*/
    protected String msgTelNotNeiMengCMCC = "您的手机号码不是内蒙古移动号码，请更换手机号码";
    /**验证手机号码出现异常的提示消息*/
    protected String msgTelException = "系统繁忙，请您稍后再试";
    /**未输入游戏名字直接输入手机号码时返回的提示消息*/
    protected String msgTelWithoutGameName = "请先输入游戏名称";

    public Game() {}

    protected Game(BaseMessage baseMessage, String content, String appKey) {
        this.baseMessage = baseMessage;
        this.content = content;
        this.appKey = appKey;
    }

    /**
     * 玩法一：微信号内输入游戏名，再输入手机号，会得到游戏的链接地址；另外可以输入会员码升级会员
     */
    public String playOne() {
        if (StringUtils.isBlank(getAppIds()) || getAppIds().contains(appKey)) {
            String result = inputMemberCode(getMemberStatus());
            if (StringUtils.isNotBlank(result)) {
                return result;
            }

            result = inputGameName();
            if (StringUtils.isNotBlank(result)) {
                return result;
            }

            result = inputTelephone();
            if (StringUtils.isNotBlank(result)) {
                return result;
            }

        }
        return "";
    }

    /**
     * 玩法二：输入包含关键字、或关键值后，得到自定义应答
     */
    public String playTwo() {
        if (StringUtils.isBlank(getAppIds()) || getAppIds().contains(appKey)) {
            if(isFocusKeyword(content)) {
                return gameUrl();
            }
        }
        return "";
    }

    /**
     * 玩法三：微信号内输入游戏名，再输入手机号，上传图片
     */
    public String playThree() {
        if (StringUtils.isBlank(getAppIds()) || getAppIds().contains(appKey)) {
            if (StringUtils.isNotBlank(baseMessage.getMsgType()) && baseMessage.getMsgType().equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
                String result = uploadImage();
                if (StringUtils.isNotBlank(result)) {
                    return result;
                }
            } else {
                String result = inputGameName();
                if (StringUtils.isNotBlank(result)) {
                    return result;
                }

                result = inputTelephone();
                if (StringUtils.isNotBlank(result)) {
                    return result;
                }
            }
        }
        return "";
    }

    private boolean isFocusKeyword(String content) {
        if (getKeyValue().equalsIgnoreCase(content)) {
            return true;
        }
        String[] strings = getKeywords().split(",");
        for (String str : strings) {
            if (content.contains(str)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 以英文逗号分割的关键字列表
     */
    protected String getKeywords(){
        return "";
    }

    /**
     * 关键值
     */
    protected String getKeyValue(){
        return "";
    }

    /**获取用户最近输入的游戏名字，用于知道输入手机号对应哪款游戏*/
    protected String getLatestInputGameName(String openId, String appKey) {
        PlayGame condition = new PlayGame();
        condition.setOpenId(openId);
        condition.setAppId(appKey);

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getLatestInputGameName", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                if (baseResponse.getData() == null) {
                    return "";
                }
                return baseResponse.getData().toString();
            }
        }
        return "";
    }

    protected String uploadImage() {
        //判断属于哪款游戏
        String currentGameName = getLatestInputGameName(baseMessage.getToUserName(), appKey);
        if (StringUtils.isBlank(currentGameName) || !currentGameName.equalsIgnoreCase(getNickName())) {
            return "";
        }

        //判断活动是否在活动期内
        TextMessage textMessage = new TextMessage(baseMessage);
        textMessage.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_TEXT);
        Date now = new Date();
        if (DateTimeUtil.compareDate(getStartDate(), now) == 1) {
            textMessage.setContent(getMsgGameNotStart());
        } else if (DateTimeUtil.compareDate(getEndDate(), now) == -1) {
            textMessage.setContent(getMsgGameIsEnd());
        } else {
            //判断今天是否输入过游戏名字和手机号
            if (!hasInputGameNameToday(baseMessage.getToUserName(), appKey)) {
                textMessage.setContent(getMsgTelWithoutGameName());
            } if(!hasInputTelToday(baseMessage.getToUserName(), appKey)) {
                textMessage.setContent(getMsgImageWithoutTel());
            } else {
                //判断微信号是否已经超过抽奖次数
                String result = wechatJoinCountToday(baseMessage.getToUserName(), appKey);
                if (StringUtils.isNotBlank(result)
                        && !isMemberTimes.equals(result)) {
                    textMessage.setContent(result);
                } else {
                    //判断手机号是否已经超过抽奖次数
                    result = telJoinCountToday(content, baseMessage.getToUserName(), appKey);
                    if (StringUtils.isNotBlank(result)) {
                        textMessage.setContent(result);
                    } else {
                        //正常参加游戏，保存图片
                        return getMsgAfterImage();
                    }
                }
            }
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    protected String inputTelephone() {
        //判断属于哪款游戏
        String currentGameName = getLatestInputGameName(baseMessage.getToUserName(), appKey);
        if (StringUtils.isBlank(currentGameName) || !currentGameName.equalsIgnoreCase(getNickName())) {
            return "";
        }

        //判断活动是否在活动期内
        TextMessage textMessage = new TextMessage(baseMessage);
        Date now = new Date();
        if (DateTimeUtil.compareDate(getStartDate(), now) == 1) {
            textMessage.setContent(getMsgGameNotStart());
        } else if (DateTimeUtil.compareDate(getEndDate(), now) == -1) {
            textMessage.setContent(getMsgGameIsEnd());
        } else {
            //判断是否是内蒙移动手机号
            int telType = ValidateUtil.isYiDong(content);
            if (telType != 0) {
                if (telType == -1) {
                    textMessage.setContent(getMsgTelNotKnow());
                } else if (telType == 1) {
                    textMessage.setContent(getMsgTelNotNeiMengCMCC());
                } else if (telType == -2) {
                    return "";
                } else if (telType == -3) {
                    textMessage.setContent(msgTelException);
                }
                return MessageUtil.textMessageToXml(textMessage);
            }

            //判断今天是否输入过游戏名字
            if (!hasInputGameNameToday(baseMessage.getToUserName(), appKey)) {
                textMessage.setContent(getMsgTelWithoutGameName());
            } else {
                //判断微信号是否已经超过抽奖次数
                String result = wechatJoinCountToday(baseMessage.getToUserName(), appKey);
                if (StringUtils.isNotBlank(result)
                        && !isMemberTimes.equals(result)) {
                    textMessage.setContent(result);
                } else {
                    //判断手机号是否已经超过抽奖次数
                    result = telJoinCountToday(content, baseMessage.getToUserName(), appKey);
                    if (StringUtils.isNotBlank(result)) {
                        textMessage.setContent(result);
                    } else {
                        //正常参加游戏，返回游戏链接地址
                        return gameUrl();
                    }
                }
            }
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    protected String inputGameName() {
        if (!content.equalsIgnoreCase(getName())) {
            return "";
        }

        //判断活动是否在活动期内
        TextMessage textMessage = new TextMessage(baseMessage);
        Date now = new Date();
        if (DateTimeUtil.compareDate(getStartDate(), now) == 1) {
            textMessage.setContent(getMsgGameNotStart());
        } else if (DateTimeUtil.compareDate(getEndDate(), now) == -1) {
            textMessage.setContent(getMsgGameIsEnd());
        } else {
            //插入playgame表，准备开始游戏
            PlayGame playGame = new PlayGame();
            playGame.setAppId(appKey);
            playGame.setOpenId(baseMessage.getToUserName());
            playGame.setGameName(getNickName());
            MyRopClient.getRopClient("").buildClientRequest()
                    .post(playGame, BaseResponse.class, "playGame.insert", "1.0");

            //判断此微信号今天是否已经参加过
            String wechatJoinCountTodayResult = wechatJoinCountToday(baseMessage.getToUserName(), appKey);
            if (StringUtils.isNotBlank(wechatJoinCountTodayResult)
                    && !isMemberTimes.equals(wechatJoinCountTodayResult)) {
                textMessage.setContent(wechatJoinCountTodayResult);
            } else {
                textMessage.setContent(getMsgAfterGameName());
            }
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    protected String inputMemberCode(Integer memberStatus) {
        if (StringUtils.isBlank(getMemberCode()) || !content.equalsIgnoreCase(getMemberCode())) {
            return "";
        }

        //判断活动是否在活动期内
        TextMessage textMessage = new TextMessage(baseMessage);
        Date now = new Date();
        if (DateTimeUtil.compareDate(getStartDate(), now) == 1) {
            textMessage.setContent(getMsgGameNotStart());
        } else if (DateTimeUtil.compareDate(getEndDate(), now) == -1) {
            textMessage.setContent(getMsgGameIsEnd());
        } else {
            //输入游戏会员码，如果存在此用户，则升级成会员；如果不存在此用户，则添加用户并升级成会员
            if (User.setUserToMember(appKey, baseMessage.getToUserName(), memberStatus)) {
                textMessage.setContent(getMsgUpgradeMemberSuccess());
            } else {
                textMessage.setContent(getMsgUpgradeMemberFailure());
            }
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    /**
     * 微信号每日参加规则
     */
    public String wechatJoinCountToday(String openId, String appKey) {
        return "";
    }

    /**
     * 手机号每日参加规则
     */
    public String telJoinCountToday(String tel, String openId, String appKey) {
        return "";
    }

    /**
     * 返回游戏链接地址的应答消息
     */
    protected abstract String gameUrl();

    /**
     * 判断微信号用户今天是否已经输入过游戏名字
     */
    public boolean hasInputGameNameToday(String openId, String appKey) {
        PlayGame condition = new PlayGame();
        condition.setAppId(appKey);
        condition.setOpenId(openId);

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getNameToday", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<String> gameNames = (List<String>)baseResponse.getData();
                for (String gameName : gameNames) {
                    if (gameName.equals(getNickName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 判断微信号用户今天是否已经输入过手机号
     */
    public boolean hasInputTelToday(String openId, String appKey) {
        PlayGame condition = new PlayGame();
        condition.setAppId(appKey);
        condition.setOpenId(openId);
        condition.setGameName(getNickName());

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getLatestInputTelToday", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<String> tels = (List<String>) baseResponse.getData();
                if (tels != null && tels.size() > 0
                        && StringUtils.isNotBlank(tels.get(0))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断是否是会员
     */
    public boolean isMember(String openId, String appKey, Integer memberStatus) {
        WechatUser userCondition = new WechatUser();
        userCondition.setAppId(appKey);
        userCondition.setOpenId(openId);
        userCondition.setStatus(Constant.STATUS_ENABLE);
        userCondition.setMemberStatus(memberStatus);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(userCondition, BaseResponse.class, "wechatUser.listAll", "1.0");
        if (response.isSuccessful()) {
            BaseResponse userResponse = response.getSuccessResponse();
            if (userResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> dataList = (List<LinkedHashMap<String, Object>>)userResponse.getData();
                if (dataList != null && dataList.size() > 0) {
                    //是会员
                    return true;
                }
            }
        }
        return false;
    }

    /**开启游戏的微信号appId；多个微信号同时开展，用逗号分隔；为空表示在全区开展*/
    public abstract String getAppIds();

    /**升级会员码。为空表示没有会员制*/
    public abstract String getMemberCode();

    /**会员的标志*/
    public abstract Integer getMemberStatus();

    /**游戏名，用户在微信中输入此名字开始游戏*/
    public abstract String getName();

    /**游戏英文名，存入数据库以区分不同的游戏*/
    public abstract String getNickName();

    /**游戏开始时间*/
    public abstract String getStartDate();

    /**游戏结束时间*/
    public abstract String getEndDate();

    public String getMsgUpgradeMemberSuccess() {
        return msgUpgradeMemberSuccess;
    }

    public String getMsgUpgradeMemberFailure() {
        return msgUpgradeMemberFailure;
    }

    public String getMsgGameNotStart() {
        return msgGameNotStart;
    }

    public String getMsgGameIsEnd() {
        return msgGameIsEnd;
    }

    public String getMsgAfterGameName() {
        return msgAfterGameName;
    }

    public String getMsgTelNotKnow() {
        return msgTelNotKnow;
    }

    public String getMsgTelNotNeiMengCMCC() {
        return msgTelNotNeiMengCMCC;
    }

    public String getMsgTelException() {
        return msgTelException;
    }

    public String getMsgTelWithoutGameName() {
        return msgTelWithoutGameName;
    }

    public String getMsgImageWithoutTel() {
        return "";
    }

    public String getMsgAfterImage() {
        return "";
    }
}
